package com.jvtd.eyl.ui.main.home.read.base;

import android.support.annotation.MainThread;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.jvtd.eventBus.EventCenter;
import com.jvtd.eyl.R;
import com.jvtd.eyl.base.BaseMvpFragment;
import com.jvtd.eyl.base.BasePresenter;
import com.jvtd.eyl.bean.binding.BookBean;
import com.jvtd.eyl.constants.EventCode;
import com.jvtd.eyl.utils.DownloadUtils;
import com.jvtd.utils.FileUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.util.Collections;
import java.util.List;

/**
 * 读取书籍详情基类
 *
 * 作者:chenlei
 * 时间:2018/11/15 9:22 AM
 */
public abstract class ReadBaseFragment extends BaseMvpFragment {
    private BasePresenter mBasePresenter;
    private BookBean mBean;

    @Override
    protected void initViewAndData() {
        EventBus.getDefault().post(new EventCenter<>(EventCode.BAN_SCROLL));
    }

    /**
     * 加载文件
     * @param basePresenter 基础presenter
     * @param bookBean 书籍信息
     */
    public void loadFile(BasePresenter basePresenter, BookBean bookBean){
        mBasePresenter = basePresenter;
//        if (TextUtils.equals(bookBean.getIsAdd(),BookBean.YES))
            addBookSuccess(Collections.singletonList(bookBean));
//        else
//            basePresenter.addBook(Collections.singletonList(bookBean));
    }

    @Override
    public void addBookSuccess(List<BookBean> bookBeans) {
        super.addBookSuccess(bookBeans);
        mBean = bookBeans.get(0);
        checkBook(mBasePresenter,mBean);
        if (FileUtils.isExistFile(mContext,mBean.getUrl(), String.format(".%s", mBean.getFileType()))){
            downloadFileSuccess();
        }else
            downloadFile(mBean.getUrl(),mBean.getFileType());
    }

    @MainThread
    public void downloadFile(String url, String fileType){
        DownloadUtils.downloadPdf(mContext,url,fileType,new FileDownloadSampleListener(){
            @Override
            protected void started(BaseDownloadTask task) {
            }

            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes)
            {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes)
            {

            }

            @Override
            protected void completed(BaseDownloadTask task)
            {
                downloadFileSuccess();
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes)
            {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e)
            {
                downloadFileFailed();
                onError(R.string.loading_failed);
            }

            @Override
            protected void warn(BaseDownloadTask task)
            {
            }
        });
    }

    public void downloadFileSuccess()
    {
        mBasePresenter.addBrowse(mBean);
    }

    public void initSuccess(){
        EventBus.getDefault().post(new EventCenter<>(EventCode.OPEN_SCROLL));
    }

    public void downloadFileFailed(){
        EventBus.getDefault().post(new EventCenter<>(EventCode.OPEN_SCROLL));
    }

    public void checkBook(BasePresenter mPresenter, BookBean mBookBean){
        if (isExistBook(mBookBean.getBookId()))
        {
            BookBean bookBean = findBook(mBookBean.getBookId());
            mBookBean.setReadNum(bookBean.getReadNum());
        }else
        {
            saveBook(mBookBean);
        }
    }

    public void onKeyDown(int keyCode, KeyEvent event){
        if (keyCode == KeyEvent.KEYCODE_BACK){
            FileDownloader.getImpl().pauseAll();
        }
    }

    /**
     * 是否已阅读当前书籍
     *
     * @author Chenlei
     * created at 2018/8/27
     **/
    public boolean isExistBook(String bookId){
        return DataSupport.isExist(BookBean.class,"userId = ? and bookId = ?", mBasePresenter.getCurrentUser().getUserId(), bookId);
    }

    /**
     * 保存当前书籍
     *
     * @author Chenlei
     * created at 2018/8/27
     **/
    public void saveBook(BookBean bookBean){
        bookBean.setUserId(mBasePresenter.getCurrentUser().getUserId());
        bookBean.setReadNum(0);
        bookBean.save();
    }

    /**
     * 更新当前书籍
     *
     * @author Chenlei
     * created at 2018/8/27
     **/
    public void updateBook(BookBean bookBean){
        bookBean.saveOrUpdate("userId = ? and bookId = ?",mBasePresenter.getCurrentUser().getUserId(),bookBean.getBookId());
    }

    /**
     * 查询当前书籍
     *
     * @author Chenlei
     * created at 2018/8/27
     **/
    public BookBean findBook(String bookId){
        return DataSupport.where("userId = ? and bookId = ?",mBasePresenter.getCurrentUser().getUserId(),bookId).findFirst(BookBean.class);
    }
}
